package com.zzyl.intercept;

import cn.hutool.core.map.MapUtil;
import cn.hutool.core.util.StrUtil;
import com.zzyl.config.JwtTokenManagerProperties;
import com.zzyl.constant.Constants;
import com.zzyl.enums.BasicEnum;
import com.zzyl.exception.BaseException;
import com.zzyl.utils.JwtUtil;
import com.zzyl.utils.UserThreadLocal;
import io.jsonwebtoken.Claims;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @Description UserInterceptor
 * @Author songyu
 * @Date 2024-10-20
 */
@Slf4j
@Component
public class UserInterceptor implements HandlerInterceptor {

    @Autowired
    private JwtTokenManagerProperties jwtTokenManagerProperties;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        //1.判断是否是处理器资源，如果不是放行
        if(!(handler instanceof HandlerMethod)){
            return true;
        }

        //2.来到这里肯定是处理器资源（控制器方法或拦截器）校验token
        //2.1 从请求头中获取token令牌
        //request.getHeader("authorization")
        String token = request.getHeader(Constants.USER_TOKEN);
        //2.2 判断令牌是否有效，无效抛出认证失败异常
        if(StrUtil.isEmpty(token)){
            throw new BaseException(BasicEnum.SECURITY_ACCESSDENIED_FAIL);
        }
        //2.3 token有效，解析token得到载荷
        Claims claims = JwtUtil.parseJWT(
                jwtTokenManagerProperties.getBase64EncodedSecretKey(),
                token
        );
        //2.4 得到载荷存储的用户id并打印
        //Long memberId = Long.valueOf(claims.get(Constants.JWT_USERID).toString());
        Long memberId = MapUtil.get(claims, Constants.JWT_USERID, Long.class);
        log.info("解析token成功，微信用户id:{}",memberId);

        //打印线程id
        log.info("==UserInterceptor的preHandle方法，线程id:{}==",Thread.currentThread().getId());
        //将登录人id存储到ThreadLocal
        UserThreadLocal.set(memberId);
        //2.5 放行
        return true;
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        //拦截响应的最终方法，在这里移除ThreadLocal存储的数据，防止内存数据泄漏给其他请求
        UserThreadLocal.remove();
    }
}
